/**
 * 
 */
package com.nari.baseinfo.service;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.nari.baseinfo.dao.IBuildingDao;
import com.nari.baseinfo.dao.IBuildingUnitDao;
import com.nari.baseinfo.dao.ICommunityDao;
import com.nari.baseinfo.dao.IFileMappingDao;
import com.nari.baseinfo.model.IBuilding;
import com.nari.baseinfo.model.IFileMapping;
import com.nari.coreframe.service.GenericServiceImpl;
import com.nari.platform.date.CalendarUtils;
import com.nari.platform.model.PageCond;
import com.nari.platform.model.ResponseMsg;
import com.nari.platform.model.ResultWithPageCond;

/**
 * 
 * @author Xiaopeng
 * @date 2013-8-1
 */
public class BuildingServiceImpl extends GenericServiceImpl<IBuilding, String>
		implements IBuildingService {
	private String diskFilePath;
	private String buildingAttachFolder;
	private IFileMappingDao iFileMappingDao;
	private IBuildingUnitDao iBuildingUnitDao;
	private ICommunityDao iCommunityDao;

	/**
	 * 分页查询楼栋信息
	 * @param buildingName 楼栋名称(可选)
	 * @param projectUID 所属项目(可选)
	 * @param communityUID 所属小区(可选)
	 * @param pageCond
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-8-8
	 */
	public ResultWithPageCond<IBuilding> queryBuildingPage(String buildingName,
			String projectUID, String communityUID, PageCond pageCond) throws Exception {
		IBuildingDao iBuildingDao = (IBuildingDao) this.getiGenericDao();
		return iBuildingDao.queryBuildingPage(buildingName, projectUID, communityUID, pageCond);
	}

	/**
	 * 带附件上传的楼栋信息保存及修改
	 * @param building 楼栋信息实体
	 * @param attachFile 楼栋附件
	 * @param fileName 附件文件名
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-8-11
	 */
	public ResponseMsg saveOrUpdateBuilding(IBuilding building, File attachFile, 
			String fileName) throws Exception {
		IBuildingDao iBuildingDao = (IBuildingDao) this.getiGenericDao();
		//统计相同楼栋编号的楼栋数量，避免系统录入相同楼栋编号的楼栋信息
		int counter = iBuildingDao.countByBuildingID(building.getBuildingID(), building.getId());
		if(counter > 0) {
			return ResponseMsg.getInstance(false, "系统中存在重复的楼栋编号，楼栋信息无法保存！");
		}
		String deleteFileMapUID = null; // 修改楼栋附件时，则删除原附件
		// 带附件上传的楼栋信息提交
		if (attachFile != null) {
			File svFile = null; // 存储磁盘附件
			try {
				// 附件存储路径对应的磁盘目录检测
				File fileSaveFolder = new File(this.diskFilePath + "/" + this.buildingAttachFolder);
				if (!fileSaveFolder.exists()) {
					fileSaveFolder.mkdirs();
				}
				// 文件名称
				String orFilename = fileName.substring(0, fileName.lastIndexOf("."));
				// 文件类型
				String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
				// 电子文件实体映射
				IFileMapping fileMapping = new IFileMapping();
				fileMapping.setOrFilename(orFilename);
				fileMapping.setDiskID(diskFilePath);
				fileMapping.setFileType(fileType);
				fileMapping.setFileSize(attachFile.length());
				fileMapping.setCreateTime(new Date());
				// 读取文件映射的唯一标识
				String fileMappingUID = this.iFileMappingDao.saveEntity(fileMapping);
				// 文件存储的随机文件名
				String svFilename = fileMappingUID
						+ "-"
						+ CalendarUtils.parseDateToString(new Date(), "yyyy-MM-dd-HH-mm-ss");
				fileMapping.setSvFilename(svFilename);
				// 文件的存储路径(相对路径)
				String savePath = this.buildingAttachFolder 
						+ "/" + svFilename
						+ "." + fileType;
				fileMapping.setSavePath(savePath);
				this.iFileMappingDao.updateEntity(fileMapping, fileMappingUID);
				// 设置楼栋附件引用信息
				deleteFileMapUID = building.getAttachPath();
				building.setAttachPath(fileMappingUID);
				// 将附件文件保存到磁盘中
				svFile = new File(this.diskFilePath + "/" + savePath);
				this.iFileMappingDao.saveUpload(attachFile, svFile);
			} catch (Exception e) {
				e.printStackTrace();
				if (svFile.exists()) {
					svFile.delete();
				}
				throw new Exception(e.getMessage());
			}
		}
		if (building != null) {
			// 保存楼栋信息
			if (building.getId() != null && !"".equals(building.getId())) {
				this.getiGenericDao().updateEntity(building, building.getId());
				// 删除楼栋原附件
				if (deleteFileMapUID != null && !"".equals(deleteFileMapUID)) {
					this.iFileMappingDao.deleteFileMapByUID(deleteFileMapUID);
				}
			} else {
				this.getiGenericDao().saveEntity(building);
			}
		}
		return ResponseMsg.getInstance(true, "");
	}

	/**
	 * 删除楼栋附件
	 * @param buildingUID
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-8-11
	 */
	public ResponseMsg deleteBuildingAttachFile(String buildingUID) throws Exception {
		IBuilding building = this.getiGenericDao().queryEntityById(buildingUID);
		// 删除文件附件
		this.iFileMappingDao.deleteFileMapByUID(building.getAttachPath());
		// 更新楼栋信息
		building.setAttachPath(null);
		this.getiGenericDao().updateEntity(building, buildingUID);
		return ResponseMsg.getInstance(true, "");
	}

	/**
	 * 通过楼栋唯一标识删除楼栋信息，并删除对应的楼栋附件,并级联删除关联信息
	 * 关联信息包括：楼栋、单元、热用户、系统用户及角色、热量表、分配表、散热器、用户分摊账单
	 * 注意：热量表数据、分配表数据等表计数据具有不可恢复性，因此不能作为级联删除的对象
	 * @param buildingUID
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-8-12
	 */
	public ResponseMsg deleteBuildingByUID(String buildingUID) throws Exception {
		IBuilding building = this.getiGenericDao().queryEntityById(buildingUID);
		// 删除楼栋附件
		if (building.getAttachPath()!=null && !"".equals(building.getAttachPath())) {
			this.iFileMappingDao.deleteFileMapByUID(building.getAttachPath());
		}
		// 级联删除关联信息
		IBuildingDao iBuildingDao = (IBuildingDao) this.getiGenericDao();
		return iBuildingDao.deleteCascadeByBuildingUID(buildingUID);
	}

	/**
	 * 通过楼栋ID列表查询楼栋信息
	 * @param idList 楼栋ID列表，若列表为空，则返回空列表
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-8-13
	 */
	public List<IBuilding> queryBuildingByIDList(List<String> idList) throws Exception {
		IBuildingDao iBuildingDao = (IBuildingDao) this.getiGenericDao();
		return iBuildingDao.queryBuildingByIDList(idList);
	}

	/**
	 * 根据楼栋所属信息（所属项目、所属小区）查询楼栋列表 若项目ID、小区ID都不存在，则返回空列表
	 * @param projectUID 所属项目
	 * @param communityUID 所属小区
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-8-12
	 */
	public List<IBuilding> queryBuildingByBelongings(String projectUID,
			String communityUID) throws Exception {
		IBuildingDao iBuildingDao = (IBuildingDao) this.getiGenericDao();
		return iBuildingDao.queryBuildingByBelongings(projectUID, communityUID);
	}

	/**
	 * 通过楼栋列表查询与之关联的小区id-communityName映射表
	 * @param buildingList 楼栋列表，若楼栋列表为空，则返回空的映射表
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-8-25
	 */
	public Map<String, String> queryReferCommunityMap(
			List<IBuilding> buildingList) throws Exception {
		List<String> communityIDList = null;
		if (buildingList != null && buildingList.size() > 0) {
			communityIDList = new ArrayList<String>();
			for (IBuilding building : buildingList) {
				communityIDList.add(building.getCommunityID());
			}
		}
		return iCommunityDao.queryIdNameMapByIDList(communityIDList);
	}
	
	/**
	 * 通过楼栋所属关系统计楼栋的个数
	 * @param projectUID 所属项目(可选)
	 * @param communityUID 所属小区(可选)
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-10-21
	 */
	public int countBuildingSumByBelongs(String projectUID, String communityUID) throws Exception {
		IBuildingDao iBuildingDao = (IBuildingDao) this.getiGenericDao();
		return iBuildingDao.countBuildingSumByBelongs(projectUID, communityUID);
	}
	
	/**
	 * 统计相同楼栋编号的楼栋数量，避免系统录入相同楼栋编号的楼栋信息
	 * @param buildingID
	 * @param buildingUID
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2014-1-22
	 */
	public int countByBuildingID(String buildingID, String buildingUID) throws Exception {
		IBuildingDao iBuildingDao = (IBuildingDao) this.getiGenericDao();
		return iBuildingDao.countByBuildingID(buildingID, buildingUID);
	}

	/**
	 * @return the iFileMappingDao
	 */
	public IFileMappingDao getiFileMappingDao() {
		return iFileMappingDao;
	}

	/**
	 * @param iFileMappingDao
	 *            the iFileMappingDao to set
	 */
	public void setiFileMappingDao(IFileMappingDao iFileMappingDao) {
		this.iFileMappingDao = iFileMappingDao;
	}

	/**
	 * @return the diskFilePath
	 */
	public String getDiskFilePath() {
		return diskFilePath;
	}

	/**
	 * @param diskFilePath
	 *            the diskFilePath to set
	 */
	public void setDiskFilePath(String diskFilePath) {
		this.diskFilePath = diskFilePath;
	}

	/**
	 * @return the buildingAttachFolder
	 */
	public String getBuildingAttachFolder() {
		return buildingAttachFolder;
	}

	/**
	 * @param buildingAttachFolder
	 *            the buildingAttachFolder to set
	 */
	public void setBuildingAttachFolder(String buildingAttachFolder) {
		this.buildingAttachFolder = buildingAttachFolder;
	}

	/**
	 * @return the iBuildingUnitDao
	 */
	public IBuildingUnitDao getiBuildingUnitDao() {
		return iBuildingUnitDao;
	}

	/**
	 * @param iBuildingUnitDao
	 *            the iBuildingUnitDao to set
	 */
	public void setiBuildingUnitDao(IBuildingUnitDao iBuildingUnitDao) {
		this.iBuildingUnitDao = iBuildingUnitDao;
	}

	/**
	 * @return the iCommunityDao
	 */
	public ICommunityDao getiCommunityDao() {
		return iCommunityDao;
	}

	/**
	 * @param iCommunityDao
	 *            the iCommunityDao to set
	 */
	public void setiCommunityDao(ICommunityDao iCommunityDao) {
		this.iCommunityDao = iCommunityDao;
	}

}
